<template>
  <el-dialog title="数据" :visible.sync="visible" width="60%" append-to-body>
    <el-button
      @click="exportWord"
      type="warning"
      plain
      icon="el-icon-download"
      style="margin: 5px"
      size="small"
      >导出word</el-button
    >

    <!-- 设备选取表格 -->
    <div class="quote_table clearfix">
      <el-table
        border
        class="table_domQuote"
        ref="tableDomQuote"
        size="small"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column
          type="index"
          width="80"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column
          label="姓名"
          prop="studentName"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="班级"
          prop="className"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column prop="povertyType" label="类型" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column
          prop="bankName"
          label="开户行"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="cardNumber"
          label="卡号"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="postComp"
          label="用工薪酬（元/小时）"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="totalHours"
          label="工时"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="comp"
          label="金额（元）"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="联系电话"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <!-- <el-table-column label="学生签名" align="center"></el-table-column> -->
      </el-table>
      注： 1.本表所有签字流程完成后原件交财务处，复印件交学生资助管理中心。</br>
      2.本表中“工时”统一按小时计算，每小时10元。金额应为工时10的倍数关系。</br>
      3.本表中“类型”分为三类：特别贫困、一般贫困或不贫困，按实际填写即可。</br>
      4.本表必须按月报送，不允许跨月、跨年报送，否则，将不予处理。</br>
      5.学生勤工助学时间一般每周不超过8小时，每月不超过40小时(寒暑假除外)。</br>
      6.本表格为excel格式，可以根据实际增加行数，但不允许私自改变表格格式。</br>
      7.该表格于2024年5月份启用，之前的表格停止使用</br>
    </div>
  </el-dialog>
</template>
<script>
import { postempsalaryList } from "@/api/worStudy/personnelPay";

import docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import JSZipUtils from "jszip-utils";
import { saveAs } from "file-saver";
import { forEach } from "jszip";
import { getDicts } from "@/api/system/dict/data";

export default {
  name: "expro",
  dicts: ["wsp_poverty_type"],
  data() {
    return {
      visible: false,
      // 表单对象
      form: {
        totalPrice: "", // 合计报价
        totalAmount: "",
        totalHours: "", // 工时
      },
      // 表格信息
      tableData: [],
      povertyTypeList: [],
    };
  },
  created() {
    getDicts("wsp_poverty_type").then((res) => {
      console.log(res, "qing");
      this.povertyTypeList = res.data;
    });
  },
  methods: {
    open() {
      this.visible = true;
      postempsalaryList({ compStatus: "Y" }).then((response) => {
        // this.tableData = response.rows;

        this.tableData = response.rows.map((item, index) => {
          return {
            number: index + 1,
            studentName: item.studentName,
            className: item.className,
            povertyType: item.povertyType || "",
            bankName: item.bankName || "",
            cardNumber: item.cardNumber || "",
            totalHours: item.wspPostEmpSalary.totalHours,
            comp: item.wspPostEmpSalary.comp,
            mobile: item.mobile || "",
            postComp: item.wspDeptPost.postComp,
          };
        });

        this.tableData.forEach((i) => {
          if (i.cardNumber == null) {
            i.cardNumber = "";
          } else if (i.bankName == null) {
            i.bankName = "";
          } else if (i.mobile == null) {
            i.mobile = "";
          } else if (i.povertyType == null) {
            i.povertyType = "";
          }
          this.povertyTypeList.forEach((j) => {
            if (j.dictValue == i.povertyType) {
              i.povertyType = j.dictLabel;
            }
          });
        });
        // 合计
        this.form.totalPrice = response.rows.reduce(
          (accumulator, current) => accumulator + current.wspPostEmpSalary.comp,
          0
        );
        this.form.totalHours = response.rows.reduce(
          (accumulator, current) =>
            accumulator + current.wspPostEmpSalary.totalHours,
          0
        );
        this.form.totalAmount = this.convertCurrency(this.form.totalPrice);
        // response.rows.forEach(i => {
        //        this.form.totalPrice =  i.wspPostEmpSalary.comp ++
        // })
        console.log(this.tableData, this.form, this.povertyTypeList, "content");
      });
    },
    convertCurrency(money) {
      var cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
      var cnIntRadice = ["", "拾", "佰", "仟"];
      var cnIntUnits = ["", "万", "亿", "兆"];
      var cnDecUnits = ["角", "分", "毫", "厘"];
      var cnInteger = "整";
      var cnIntLast = "元";
      var maxNum = 999999999999999.9999;
      var integerNum;
      var decimalNum;
      var chineseStr = "";
      var parts;
      if (money === "") {
        return "";
      }
      money = parseFloat(money);
      if (money >= maxNum) {
        return "";
      }
      if (money === 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
      }
      money = money.toString();
      if (money.indexOf(".") === -1) {
        integerNum = money;
        decimalNum = "";
      } else {
        parts = money.split(".");
        integerNum = parts[0];
        decimalNum = parts[1].substr(0, 4);
      }
      if (parseInt(integerNum, 10) > 0) {
        var zeroCount = 0;
        var IntLen = integerNum.length;
        for (var i = 0; i < IntLen; i++) {
          var n = integerNum.substr(i, 1);
          var p = IntLen - i - 1;
          var q = p / 4;
          var m = p % 4;
          if (n === "0") {
            zeroCount++;
          } else {
            if (zeroCount > 0) {
              chineseStr += cnNums[0];
            }
            zeroCount = 0;
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
          }
          if (m === 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q];
          }
        }
        chineseStr += cnIntLast;
      }
      if (decimalNum !== "") {
        var decLen = decimalNum.length;
        for (i = 0; i < decLen; i++) {
          n = decimalNum.substr(i, 1);
          if (n !== "0") {
            chineseStr += cnNums[Number(n)] + cnDecUnits[i];
          }
        }
      }
      if (chineseStr === "") {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
      } else if (decimalNum === "") {
        chineseStr += cnInteger;
      }
      return chineseStr;
    },

    // 点击导出word
    exportWord() {
      let _this = this;
      // 读取并获得模板文件的二进制内容
      JSZipUtils.getBinaryContent("/index.docx", (error, content) => {
        // input.docx是模板。我们在导出的时候，会根据此模板来导出对应的数据
        // 抛出异常
        if (error) {
          throw error;
        }

        // 创建一个JSZip实例，内容为模板的内容

        // let zip = new PizZip(content);
        let zip = new PizZip(content);
        // 创建并加载docxtemplater实例对象
        let doc = new docxtemplater().loadZip(zip);
        // 设置模板变量的值
        doc.setData({
          ..._this.form,
          table: _this.tableData,
        });
        console.log(doc, _this.tableData, "content");

        try {
          // 用模板变量的值替换所有模板变量
          doc.render();
        } catch (error) {
          // 抛出异常
          let e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties,
          };
          console.log(JSON.stringify({ error: e }));
          throw error;
        }

        // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
        let out = doc.getZip().generate({
          type: "blob",
          mimeType:
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        });
        // 将目标文件对象保存为目标类型的文件，并命名
        saveAs(out, "勤工俭学学生考勤表");
      });
    },
  },
};
</script>